<?php

namespace App\Http\Controllers\Api;

use App\Address;
use App\Coupon;
use App\Delivery;
use App\Events\SalesNumber;
use App\Goods;
use App\Integral;
use App\Order;
use App\OrderAction;
use App\OrderGoods;
use App\SpecGoodsPrice;
use App\TeamActivity;
use App\TeamFollow;
use App\TeamFound;
use App\UserCoupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class OrderController extends BaseController
{
    protected $jifenbili = 0.01; //todo
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Order::orderBy($orderBy, $orderType);
        if ($request->has('pay_status') && $request->pay_status != '') {
            $lists->where('pay_status', $request->pay_status);
        }
        if ($request->has('shipping_status') && $request->shipping_status != '') {
            $lists->where('shipping_status', $request->shipping_status);
        }
        if ($request->has('order_status') && $request->order_status != '') {
            $lists->where('order_status', $request->order_status);
        }
        if ($request->order_sn) {
            $lists->where('order_sn', $request->order_sn);
        }
        return $lists->with(['orderGoods'])->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        $userId = $user->id;
        $action = $request->get('action');
        $carts = $request->get('cart');
        $integral = $request->get('integral');
        if (!$carts || !is_array($carts) || empty($carts)) {
            return response(['message' => '请选择商品'], 400);
        }
        if (!$request->get('address_id') || !$address = Address::find($request->get('address_id'))) {
            return response(['message' => '请选择收货地址'], 400);
        }
        // 计算满减金额
        $dataArr = [];
        $totalFullCut = 0;
        $totalAmount = 0;
        $couponPrice = 0;
        $orderAmount = 0;
        $shippingPrice = 0;
        $integralPrice = 0;
        $totalAvailableIntegral = 0;
        $promotionAmount = 0;
        $productNum = 0;
        $zhuangbi = 0;
        $qingbi = 0;

        // 订单活动
        $promotionType = null;
        $promotionId = 0;
        $userCoupon = null;

        foreach($carts as $key => $cart) {
            $goods = Goods::where('id', $cart['goods_id'])
                ->select('id', 'name', 'stock', 'price', 'full_cut', 'give_integral', 'is_on_sale', 'exchange_integral', 'is_on_sale', 'thumb_img as thumb')
                ->with(['underwayFlashSale', 'underwayTeamActivity'])
                ->first();
            if (!$goods->is_on_sale) {
                return response(['message' => '下手慢了，商品"'.$goods->name.'"已下架'], 400);
            }
            // 商品规格
            $stock = $goods->stock;
            $price = $goods->price;
            $quantity = $cart['quantity'];
            if ($quantity <= 0) {
                return response(['商品数量错误'], 400);
            }
            if ($cart['spec_goods_price_id']) {
                $spec = SpecGoodsPrice::where('id', $cart['spec_goods_price_id'])->where('goods_id', $goods->id)->first();
                if (!$spec) {
                    return response(['message' => '商品规格选择错误，请重新选择商品'], 400);
                }
                $stock = $spec->stock;
                $price = $spec->price;
                $dataArr[$key]['spec_key'] = $spec->key;
                $dataArr[$key]['spec_value'] = $spec->value;
            }
            // 商品库存
            if ($stock < $quantity) {
                return response(['message' => '下手慢了，商品"'.$goods->name.'"库存不足'], 400);
            }

            // flashSales
            if ($goods->underwayFlashSale && $action !="team_activity") {
                $price = $price - $goods->underwayFlashSale->discount;
                $dataArr[$key]['promotionable_type'] = 'App\FlashSale';
                $dataArr[$key]['promotionable_id'] = $goods->underwayFlashSale->id;
            }

            //teamActivity
            if ($goods->underwayTeamActivity && $action == 'team_activity') {
                $price = $price - $goods->underwayTeamActivity->discount;
                $dataArr[$key]['promotionable_type'] = 'App\TeamActivity';
                $dataArr[$key]['promotionable_id'] = $goods->underwayTeamActivity->id;

                $promotionType = 'App\TeamActivity';
                $promotionId = $goods->underwayTeamActivity->id;
            }
            // 商品满减, 针对单品
            $fullCut = 0;
            if ($goods->full_cut) {
                foreach ($goods->full_cut as $cut) {
                    if ($cart['quantity'] * $price >= $cut['amount']) {
                        $fullCut = $cut['price'];
                        break;
                    }
                }
            }
            $dataArr[$key]['user_id'] = $userId;
            $dataArr[$key]['goods_price'] = $price;
            $dataArr[$key]['goods_num'] = $quantity;
            $dataArr[$key]['full_cut_price'] = $fullCut;
            $dataArr[$key]['give_integral'] = $goods->give_integral;
            $dataArr[$key]['goods_id'] = $goods->id;
            $dataArr[$key]['goods_name'] = $goods->name;
            $dataArr[$key]['goods_thumb'] = $goods->thumb;

            $totalFullCut += $fullCut;
            $totalAvailableIntegral += $goods->exchange_integral;
            $totalAmount += $price * $cart['quantity'];
            $productNum += $quantity;
        }
        // 使用积分
        if ($totalAvailableIntegral < $integral || $integral > $user->integral) {
            return response(['message' => '积分数据使用异常，请刷新重试'], 400);
        }
        $integralPrice = $integral * $this->jifenbili;

        // 使用优惠券
        if ($request->get('user_coupon_id')) {
            $userCoupon = UserCoupon::where('id', $request->get('user_coupon_id'))->where('user_id', Auth::id())->first();
            if ($userCoupon &&
                $userCoupon->used_at == null &&
                $userCoupon->start_use_at < Carbon::now() &&
                $userCoupon->end_use_at > Carbon::now() &&
                $userCoupon->use_scope == 'ALL' &&
                $userCoupon->mini_consumption < $totalAmount) {
                $couponPrice = $userCoupon->money;
            }
        }
        // 会员折扣
        $discountPrice = 0;
        $discount = $user->level->discount;
        if ($discount > 0 && $action != 'zhuangbi_buy' && $action != 'qingbi_buy') {
            $discountPrice = $totalAmount * (1 - $discount);
        }
        $orderAmount = $totalAmount - $discountPrice - $integralPrice - $totalFullCut - $couponPrice - $shippingPrice - $promotionAmount;

        // 币兑换
        if ($action == 'zhuangbi_buy') {
            $zhuangbi = ceil($orderAmount);
            if ($user['zhuangbi'] < $zhuangbi) {
                return response(['message' => '装币不足'], 400);
            }
            $orderAmount = 0;
        }
        if ($action == 'qingbi_buy') {
           $goods = Goods::find($dataArr[0]['goods_id']);
           $qingbi = $goods->qingbi_number;
            if ($user['qingbi'] < $qingbi) {
                return response(['message' => '轻币不足'], 400);
            }
            $orderAmount = $orderAmount - $qingbi;
        }

        if ($orderAmount < 0) {
            $orderAmount = 0;
        }
        // 余额
        if ($request->pay_type == 'BALANCE' && $user->balance < $orderAmount) {
            return response(['message' => '余额不足'], 400);
        }
        // 创建订单
        $data = [
            'user_id' => $userId,
            'order_sn' => $this->generateOrderSn(),
            'consignee' => $address->consignee,
            'province' => $address->province,
            'city' => $address->city,
            'district' => $address->district,
            'address' => $address->address,
            'phone' => $address->phone,
            'zip_code' => $address->zip_code,
            'integral' => $integral,
            'discount' => $discountPrice,
            'integral_price' => $integralPrice,
            'coupon_price' => $couponPrice,
            'full_cut_price' => $totalFullCut,
            'total_amount' => $totalAmount,
            'order_amount' => $orderAmount,
            'shipping_price' => $shippingPrice,
            'qingbi_price' => $qingbi,
            'zhuangbi_price' => $zhuangbi,
            'pay_code' => $request->pay_code,
            'pay_name' => config('pay.'.strtoupper($request->pay_code)),
            'promotion_amount' => $promotionAmount,
            'product_num' => $productNum,
            'order_status' => 'UNCONFIRMED',
            'pay_status' => 0,
            'shipping_status' => 0,
            'promotion_type' => $promotionType,
            'promotion_id' => $promotionId
        ];
        if ($data['order_amount'] == 0) {
            $data['pay_status'] = 1;
            $data['paid_at'] = Carbon::now();
        }
        $order = Order::create($data);
        if ($order) {
            // 发起拼团
            if ($order->promotion_type == 'App\TeamActivity') {
                $teamFoundId = intval($request->team_found_id);
                if (!$teamFoundId) {
                    $activity = TeamActivity::where('id', $order->promotion_id)->where('status', 1)->first();
                    if (!$activity || $activity->status != 1) {
                        $order->delete();
                        return response(['message' => '来晚了，当前活动已结束'], 400);
                    }
                    $found = TeamFound::create([
                        'user_id' => $userId,
                        'team_activity_id' => $order->promotion_id,
                        'needer' => $activity->needer,
                        'ended_at' => Carbon::now()->addHours($activity->time_limit),
                        'join' => $order->order_amount == 0 ? 1 : 0,
                        'order_id' => $order->id,
                        'status' => $order->order_amount == 0 ? 'ACTIVE' : 'UNPAID'
                    ]);
                    $teamFoundId = $found->id;
                } else { // 参团
                    $teamFound = TeamFound::where('id', $teamFoundId)->first();
                    if (!$teamFound || $teamFound->status != 'ACTIVE' || $teamFound->ended_at < Carbon::now()) {
                        $order->delete();
                        return response(['message' => '来晚了，当前拼团已结束'], 400);
                    }
                }
                TeamFollow::create([
                    'user_id' => $userId,
                    'team_found_id' => $teamFoundId,
                    'order_id' => $order->id,
                    'team_found_user_id' => $order->user_id
                ]);
            }

            // 使用积分处理
            if ($integral > 0) {
                $user->integral = $user->integral - $integral;
                Integral::create(['user_id' => $userId, 'number' => $integral, 'type' => 2, 'description' => '购物消费']);
                $user->save();
            }

            // 轻币兑换处理
            if ($qingbi > 0) {
                $user->qingbi = $user->qingbi - $qingbi;
                Integral::create(['user_id' => $userId, 'number' => $qingbi, 'type' => 2, 'category' => 2, 'description' => '兑换商品']);
                $user->save();
            }
            // 装兑换处理
            if ($zhuangbi > 0) {
                $user->zhuangbi = $user->zhuangbi - $zhuangbi;
                Integral::create(['user_id' => $userId, 'number' => $zhuangbi, 'type' => 2, 'category' => 3, 'description' => '兑换商品']);
                $user->save();
            }

            // 使用优惠券处理
            if ($couponPrice > 0 && $userCoupon != null) {
                $userCoupon->used_at = Carbon::now();
                $userCoupon->order_id = $order->id;
                $userCoupon->save();
                Coupon::where('id', $userCoupon->coupon_id)->increment('used_num');
            }
            // 创建订单商品
            foreach ($dataArr as $goods) {
                $order->orderGoods()->create($goods);
            }
            // 统计销量及库存
            event(new SalesNumber($order, 1));
            // 创建订单日志
            OrderAction::newAction($order, ['action' => '下单成功', 'note' => '您提交了订单，请等待系统确认', 'user_id' => $userId]);
        }

        return $order;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function show(Order $order)
    {
        return $order = Order::where('id', $order->id)
            ->with(['user', 'orderGoods', 'actions' => function($query) {
                return $query->orderBy('id', 'desc');
            }, 'actions.user', 'teamFollow.teamFound'])
            ->first();
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function edit(Order $order)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Order $order)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function destroy(Order $order)
    {
        //
    }

    /**
     * 生成订单编号
     * @return null|string
     */
    protected function generateOrderSn() {
        $orderSn = null;
        // 保证不会有重复订单号存在
        while(true){
            $orderSn = date('YmdHis').rand(1000,9999); // 订单编号
            $sn = Order::where("order_sn", $orderSn)->first();
            if(!$sn)
                break;
        }
        return $orderSn;
    }


    public function userOrder(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Order::orderBy($orderBy, $orderType);
        if ($request->has('pay_status') && $request->pay_status != '') {
            $lists->where('pay_status', $request->pay_status);
        }
        if ($request->has('shipping_status') && $request->shipping_status != '') {
            $lists->where('shipping_status', $request->shipping_status);
        }
        if ($request->has('order_status') && $request->order_status != '') {
            $lists->where('order_status', $request->order_status);
        }
        $order = $lists->where('user_id', Auth::id())->with('orderGoods')->latest()->paginate($pageSize);
        return $order;
    }

    public function delivery(Request $request, Order $order)
    {
        if ( count($request->get('shipping_goods')) < 0) {
            return response(['message' => '请选择发货的商品']);
        }
        $order = Order::findOrFail($request->get('order_id'));
        if ($order->shipping_status == 1) {
            return response(['message' => '商品已发货，请无重复操作'], 400);
        }
        // 创建发货单
        $delivery = Delivery::create([
            'shipping_code' => $request->get('shipping_code'),
            'shipping_no' => $request->get('shipping_no'),
            'shipping_name' => config('logistics.'.$request->get('shipping_code')),
            'order_id' => $request->get('order_id')
        ]);
        OrderGoods::whereIn('id', $request->get('shipping_goods'))->update(['delivery_id' => $delivery->id, 'status' => 1]);
        // 查询是否有未发货的商品, 修改订单发货状态
        $unshipped = OrderGoods::where('order_id', $order->id)->where('status', '<>', 1)->first();
        if ($unshipped) {
            $order->shipping_status = 2;
        } else {
            $order->shipping_status = 1;
        }
        $order->save();
        // 操作记录
        OrderAction::newAction($order, ['action' => '订单已发货', 'user_id' => Auth::id(), 'note' => $request->get('note', '商品发货成功')]);
        return response(['message' => '发货成功']);
    }

    public function confirm(Request $request, Order $order)
    {
        if ($order->order_status != 'UNCONFIRMED') {
            return response(['message' => '当前订单的状态为'.$order->order_status_desc, '无需确认'], 400);
        }
        // 订单未支付且付款方式不是货到付款
        if ($order->pay_status != 1 && $order->pay_code != 'COD') {
            return response(['message' => '该订单尚未付款，不能确认'], 400);
        }
        $order->order_status = 'CONFIRMED';
        $order->save();
        OrderAction::newAction($order, ['user_id'=> Auth::id(), 'action' => '确认订单', 'note' => $request->get('note', '订单已确认')]);
        return response(['message' => '确认成功']);
    }

    // 确认收货
    public function finish(Order $order)
    {
        if ($order->order_status != 'CONFIRMED' && $order->shipping_status != 1) {
            return response(['message' => '非法操作'], 400);
        }
        $order->order_status = 'FINISHED';
        $order->save();
        // 操作记录
        OrderAction::newAction($order, ['action' => '确认收货', 'user_id' => Auth::id(), 'note' => '您与完成收货，订单已完成~']);
        return response(['message' => '收货成功']);
    }
}
